/**
 * 类名：点单服务订单管理业务类
 * 备注：负责点单服务订单管理业务逻辑。
 * 作者：rankin
 * 日期：2016/03/10
 */
var CafeCategory = require('../models/CafeCategory');
var CafeOrder = require('../models/CafeOrder');
var Page = require('../models/page');

var config = require('../config/settings');

var ObjectID = require('mongodb').ObjectID;
var debug = require('debug')('controller:cafeorder');
var async = require('async');
var _ = require('underscore');


//数据库错误响应
function handleError(err, res) {
    debug('Happend error response fail to client. [%o]', err);
    res.send({success: false, msg: err});
};

module.exports = {

    /**
     * 点单服务订单列表页
     * @param req
     * @param res
     */
    list: function (req, res) {

        //获取参数
        var num = req.query.num || 0;
        var user_nickname = req.query.nick_name || '';
        var pass_code = req.query.pass_code || '';
        var trade_no = req.query.trade_no || '';

        //设置查询条件
        var page = new Page(num);
        var query = {};

        if (user_nickname) {    //设置用户昵称
            query.user_nickname = /'+user_nickname+'/i;
        }
        if (trade_no) {    //设置订单号
            query.trade_no = /'+trade_no+'/i;
        }
        if (pass_code) {    //设置取餐密码
            query.pass_code = /'+pass_code+'/i;
        }
        if (!req.session.permissionMap[4011]) {//没有4011权限，则需要按用户查询
            query.system_user_id = req.session.user._id;
        }

        debug('The CafeOrder query is [%o].', query);

        async.waterfall(
            [
                function (callback) {
                    //查询订单数量
                    CafeOrder.count(query, callback);
                },
                function (total, callback) {
                    //查询订单
                    CafeOrder.find(query, null, {
                        skip: page.skipFrom,
                        limit: page.limit,
                        sort: {create_date: -1}
                    }, function (err, orders) {
                        if (err) {
                            callback(err);
                        } else {
                            callback(null, {
                                total: total,
                                orders: orders
                            });
                        }
                    });
                }
            ],
            function (err, result) {
                if (err) {
                    handleError(err, res);
                    return;
                }
                //计算分页
                var pageCount = Math.ceil(result.total / page.limit);
                //响应数据
                res.render('cafe/order_list', {
                    pageCount: pageCount,
                    orders: result.orders
                });
            }
        )
        ;
    },
    /**
     * 删除订单
     * @param req
     * @param res
     */
    remove: function (req, res) {

        debug('Got a request to [do_edit],request params is [%o],body is [%o].', req.params, req.body);

        //获取请求参数
        var order_id = req.params.id;

        //数据格式验证
        if (!order_id) {    //ID必须不为空
            res.send({success: false, msg: '订单ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }

        //查询订单
        CafeOrder.findOne({trade_no: order_id}, function (err, doc) {
            if (err) {
                handleError(err, res);
                return;
            }

            //判断订单是否存在
            if (!doc) {//查询不到订单
                res.send({success: false, msg: '订单ID查询不到订单.'});
                debug('The parameter "id" do not exists in DB，response fail to client.');
                return;
            }

            //删除订单
            doc.remove(function (err) {
                if (err) {
                    handleError(err, res);
                    return;
                }
                //删除订单成功
                res.redirect('/cafe/order/list');
                debug('The CafeOrder was deleted，response succesfull to client.');
            });
        });
    }
};

